package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.my_order_list.chlid

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.album.view.grid_view.XGridLayout
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.library_common.utils.upload_file.UploadFileWorker
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.SstShopOrderChild
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.my_order_list.chlid.bean.OrderInfoBean
import com.example.wallet.bean.UserInfoWrapper
import com.example.wallet.db.UserInfoManager
import org.greenrobot.eventbus.EventBus
import java.lang.StringBuilder

/**
 * 申请退款
 * */
class DrawbackFragment : BaseFragmentEx() {

    companion object {
        fun newInstance(orderId: String): DrawbackFragment {
            val args = Bundle()
            args.putString("orderId", orderId)
            val fragment = DrawbackFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var orderId: String? = ""

    private var drawbackAddImg = DrawbackAddImgFragment.newInstance()

//    private lateinit var icon: ImageView
//
//    private lateinit var name: TextView
//
//    private lateinit var typeTv: TextView
//
//    private lateinit var priceTv: TextView

    private lateinit var mAllPriceTv: TextView

    private lateinit var contentDesc: EditText

    private var orderInfo: OrderInfoBean? = null

    private val iconType = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private lateinit var mDrawBack: View

    private lateinit var mXGridLayout: XGridLayout

    private var mUploadFileWorker: UploadFileWorker? = null

    private var mAdapter: CommAdapter<SstShopOrderChild>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        orderId = arguments?.getString("orderId", "")
    }

    override fun getLayoutId(): Any {
        return R.layout.draw_back_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = "申请退货"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }
        contentDesc = view.findViewById(R.id.contentDesc)
        mDrawBack = view.findViewById(R.id.mDrawBack)

        mXGridLayout = view.findViewById(R.id.mXGridLayout)

        mAdapter = object : CommAdapter<SstShopOrderChild>
            (_mActivity, R.layout.draw_back_fragment_item) {
            override fun convert(
                holder: XQuickViewHolder?,
                item: SstShopOrderChild?,
                position: Int
            ) {
                holder?.setText(R.id.name, item?.goodsName)
                    ?.setText(R.id.typeTv, "${item?.goodsColor} ${item?.goodsSize}")
                    ?.setText(R.id.priceTv, "${item?.goodsPrice.toString()} $iconType")
                    ?.setText(R.id.countTv, "x${item?.goodsNums} ")
                    ?.displayImage(R.id.icon, item?.goodsLogo)
            }

        }
        mXGridLayout.setAdapter(mAdapter, lifecycle)

        mAllPriceTv = view.findViewById(R.id.mAllPriceTv)

        loadRootFragment(R.id.img_cover, drawbackAddImg)

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val map = mapOf(
            "orderId" to orderId,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryOrderInfoById)
            .success {
                parseOrderInfo(it)
            }.failure {
                Toast.makeText(_mActivity, "获取订单信息失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
        mDrawBack.setOnClickListener {
            if (mUploadFileWorker == null) {
                upLoadImg()
            } else {
                Toast.makeText(_mActivity, "正在发送", Toast.LENGTH_SHORT).show()
            }

//            toApplyDrawBack()
        }
    }

    private fun upLoadImg() {
        val selector = drawbackAddImg.getSelector()

        if (selector.isEmpty()) {
            toApplyDrawBack("")
            return
        }

        val mutableListOf = mutableListOf<String>()

        for (e in selector) {
            mutableListOf.add(e.path)
        }

        mUploadFileWorker = UploadFileWorker()
        mUploadFileWorker?.setListener(object : UploadFileWorker.UpLoadOverListener {
            override fun onUpLoadOver(res: List<String>) {
                mUploadFileWorker = null
                var str = StringBuilder()
                for (w in res) {
                    str.append(w)
                        .append(",")
                }

                if (str.isNotEmpty()) {
                    str = str.deleteCharAt(str.lastIndexOf(","))
                }

                toApplyDrawBack(str.toString())
            }
        })?.doWork(mutableListOf)
    }

    private fun toApplyDrawBack(pics: String) {

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val map = mapOf(
            "contentDesc" to contentDesc.text.toString(),
            "orderId" to orderInfo?.orderId,
            "pics" to pics,
            "reason" to "",
            "uid" to userInfo?.uid
        )

        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.orderRefund)
            .success {
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
                startWithPop(DrawbackSucceedFragment.newInstance())
            }
            .failure {

            }.error { code, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    @SuppressLint("SetTextI18n")
    private fun parseOrderInfo(it: String?) {
        val obj = JSON.parseObject(it)
        val order = obj["order"].toString()
        orderInfo = JSON.parseObject(order, OrderInfoBean::class.java)


        var cost = 0.0
        if (orderInfo?.isChild == 0) {
            cost = (orderInfo?.goodsPrice ?: 0.0) * (orderInfo?.goodsNums ?: 0)
            val child = SstShopOrderChild()
            child.createTime = orderInfo?.createTime
            child.goodsColor = orderInfo?.goodsColor
            child.goodsId = orderInfo?.goodsId ?: 0
            child.goodsLogo = orderInfo?.goodsLogo
            child.goodsName = orderInfo?.goodsName
            child.goodsNums = orderInfo?.goodsNums ?: 0
            child.goodsPrice = orderInfo?.goodsPrice ?: 0.0
            child.orderId = orderInfo?.orderId ?: 0
            child.goodsSize = orderInfo?.goodsSize
            child.orderStatus = orderInfo?.orderStatus ?: 0
            orderInfo?.childOrds?.add(child)

        } else if (orderInfo?.isChild == 1) {

            for (en in orderInfo?.childOrds ?: emptyList<SstShopOrderChild>()) {
                cost += en.goodsPrice * en.goodsNums
            }
        }

        mAllPriceTv.text = "$cost $iconType"

        mAdapter?.addAll(orderInfo?.childOrds)
        mXGridLayout.maxItem =orderInfo?.childOrds?.size?:0
    }
}